package com.atguigu.ditu3.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.os.Bundle;

import android.os.Environment;
import android.provider.Settings;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.atguigu.ditu3.BNDemoGuideActivity;
import com.atguigu.ditu3.GPSinfoDao;
import com.atguigu.ditu3.GpsInfo;
import com.atguigu.ditu3.MainActivity;
import com.atguigu.ditu3.R;
import com.atguigu.ditu3.activity.bean.dingwei;
import com.atguigu.ditu3.utils.Constant;
import com.atguigu.ditu3.utils.MyUtils;
import com.atguigu.ditu3.utils.SpUtils;
import com.atguigu.ditu3.utils.zhuiguiji;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;

import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.baidu.navisdk.adapter.BNCommonSettingParam;
import com.baidu.navisdk.adapter.BNRoutePlanNode;
import com.baidu.navisdk.adapter.BNaviSettingManager;
import com.baidu.navisdk.adapter.BaiduNaviManager;
import com.google.gson.Gson;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.OnResponseListener;
import com.yolanda.nohttp.Request;
import com.yolanda.nohttp.RequestMethod;
import com.yolanda.nohttp.RequestQueue;
import com.yolanda.nohttp.Response;
import org.json.JSONException;
import org.json.JSONObject;


import java.io.File;
import java.util.ArrayList;
import java.util.List;

import static com.atguigu.ditu3.MainActivity.ROUTE_PLAN_NODE;
import static com.baidu.navisdk.adapter.BNRoutePlanNode.CoordinateType.GCJ02;


public class nowdingwei extends Activity {
    private MapView mMapView;
    private BaiduMap mBaiduMap;
    private Button backl;
    private  LatLng ne;
    private dingwei  ak;
    private LocationClient locationClient;
    private  LatLng latlngl;
    private static final String APP_FOLDER_NAME = "BNSDKSimpleDemo";
    private String mSDCardPath = null;
    private ArrayList<PoiInfo>  poiInfos;

    public static final String ROUTE_PLAN_NODE = "routePlanNode";
    public static final String SHOW_CUSTOM_ITEM = "showCustomItem";
    public static final String RESET_END_NODE = "resetEndNode";
    public static final String VOID_MODE = "voidMode";
    private final static String authBaseArr[] =
            {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_FINE_LOCATION};
    private final static String authComArr[] = {Manifest.permission.READ_PHONE_STATE};
    private final static int authBaseRequestCode = 1;
    private final static int authComRequestCode = 2;
    private boolean hasInitSuccess = false;
    private boolean hasRequestComAuth = false;
    private LocationManager lm;
    private boolean isFirst=true;
    @Override
    protected void onCreate( Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SDKInitializer.initialize(getApplicationContext());

        setContentView(R.layout.activity_nowdingwei);
        mMapView= (MapView) findViewById(R.id.id_bmapView);
        mBaiduMap=mMapView.getMap();
        backl= (Button) findViewById(R.id.back);
        Button btn= (Button) findViewById(R.id.btn);
        backl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(18.0f);
        mBaiduMap.setMapStatus(msu);

        initView();
        lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                    Toast.makeText(nowdingwei.this, "请开启GPS导航...", Toast.LENGTH_SHORT).show();
                    // 返回开启GPS导航设置界面
                    Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    startActivityForResult(intent, 0);

                    return;
                }

                if (lm.isProviderEnabled(LocationManager.GPS_PROVIDER)&&latlngl!=null) {
                    routeplanToNavi(true);
                }

            }
        });



        if (initDirs()) {
            initNavi();
        }


        lacate();


    }







    private void initView(){

        MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(18.0f);
        mBaiduMap.setMapStatus(msu);
        locationClient = new LocationClient(nowdingwei.this);
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);// 设置定位模式
        option.setCoorType("bd09ll");// 返回的定位结果是百度经纬度，默认值gcj02
        option.setScanSpan(4000);// 设置发起定位请求的间隔时间为5000ms
        option.setOpenGps(true);
        option.setIsNeedAddress(true);// 返回的定位结果包含地址信息
        // option.setNeedDeviceDirect(true);// 返回的定位结果包含手机机头的方向
        locationClient.setLocOption(option);
        //根据给定增量缩放地图级别
//


//        Toast.makeText(nowdingwei.this,"16565",Toast.LENGTH_SHORT).show();
        String phone=getIntent().getStringExtra("phone");
        dingwei kk=new dingwei();
        kk.setPhone(phone);
        getlist_3(kk, Constant.GET_NOW_GUIJI);



    }



    private void getlist_3(Object object, String url) {
        RequestQueue queue = NoHttp.newRequestQueue();
        Request<String> request = NoHttp.createStringRequest(url, RequestMethod.POST);
        Gson gson = new Gson();
        String json = gson.toJson(object);
        request.add("lrs", json);
        queue.add(88, request, new OnResponseListener<String>() {
            @Override
            public void onStart(int i) {

            }

            @Override
            public void onSucceed(int i, Response<String> response) {


                parseUserInfok(response.get());

            }

            @Override
            public void onFailed(int i, String s, Object o, Exception e, int i1, long l) {
                MyUtils.Toast(getApplication(), "轨迹");
            }

            @Override
            public void onFinish(int i) {

            }
        });
    }

    private void parseUserInfok(String result) {
        if (result != null) {
            ak = new dingwei();
            try {
                JSONObject ll = new JSONObject(result);
                ak.setLatitude((ll.optString("latitude")));
                ak.setLongitude(ll.optString("longitude"));
                ak.setPhone(ll.optString("phone"));


            } catch (JSONException e) {
                e.printStackTrace();

            }
            if (ak != null) {
                try {
                    ne = new LatLng(Double.parseDouble(ak.getLongitude()), Double.parseDouble(ak.getLatitude()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if(ne!=null) {
                    mBaiduMap.clear();
                    OverlayOptions optionll = new MarkerOptions().position(ne)
                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.icon_point));
                    mBaiduMap.addOverlay(optionll);
                    MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ne);
                    mBaiduMap.setMapStatus(u);
//            MapStatus mMapStatus = new MapStatus.Builder()
//                    .zoom(18.0f).build();
                    MapStatus mMapStatus = new MapStatus.Builder()
                            .zoom(18.0f).build();
                    // 定义MapStatusUpdate对象，以便描述地图状态将要发生的变化
                    MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory
                            .newMapStatus(mMapStatus);
                    mBaiduMap.setMapStatus(mMapStatusUpdate);
                }
            }
        }


    }





    private void lacate() {
        locationClient.registerLocationListener(new BDLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation bdLocation) {

                if (bdLocation!= null) {
//                    MyLocationData data = new MyLocationData.Builder()
//                            .direction(mX)//方向的值
//                            .accuracy(bdLocation.getRadius())
//                            .latitude(bdLocation.getLatitude())
//                            .longitude(bdLocation.getLongitude())
//                            .build();

                    double latitude = bdLocation.getLatitude();
                    double longitude = bdLocation.getLongitude();
                    LatLng latln = new LatLng(latitude,longitude);
                    MyLocationData data = new MyLocationData.Builder()
                            .accuracy(bdLocation.getRadius())
                            .latitude(bdLocation.getLatitude())
                            .longitude(bdLocation.getLongitude())
                            .build();
                    mBaiduMap.setMyLocationData(data);
//                    Toast.makeText(nowdingwei.this,latitude+"16565",Toast.LENGTH_SHORT).show();
                    getdata(latln);
                    if (isFirst) {

                        latlngl = new LatLng(latitude, longitude);
                        isFirst=false;
                        // dingzhibianhua(bdLocation);

                    }
                }
            }

            @Override
            public void onConnectHotSpotMessage(String s, int i) {

            }
        });
    }

    private String getSdcardDir() {
        if (Environment.getExternalStorageState().equalsIgnoreCase(Environment.MEDIA_MOUNTED)) {
            return Environment.getExternalStorageDirectory().toString();
        }
        return null;
    }
    private boolean initDirs() {
        mSDCardPath = getSdcardDir();
        if (mSDCardPath == null) {
            return false;
        }
        File f = new File(mSDCardPath, APP_FOLDER_NAME);
        if (!f.exists()) {
            try {
                f.mkdir();
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
        return true;
    }
    String authinfo = null;
    private boolean hasBasePhoneAuth() {
        // TODO Auto-generated method stub

        PackageManager pm = this.getPackageManager();
        for (String auth : authBaseArr) {
            if (pm.checkPermission(auth, this.getPackageName()) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }
    private boolean hasCompletePhoneAuth() {
        // TODO Auto-generated method stub

        PackageManager pm = this.getPackageManager();
        for (String auth : authComArr) {
            if (pm.checkPermission(auth, this.getPackageName()) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }
    private void initNavi() {
        // 申请权限
        if (android.os.Build.VERSION.SDK_INT >= 23) {

            if (!hasBasePhoneAuth()) {

                this.requestPermissions(authBaseArr, authBaseRequestCode);
                return;
            }
        }
        BaiduNaviManager.getInstance().init(this, mSDCardPath, APP_FOLDER_NAME, new BaiduNaviManager.NaviInitListener() {
            @Override
            public void onAuthResult(int status, String msg) {
                if (0 == status) {
                    authinfo = "key校验成功!";
                } else {
                    authinfo = "key校验失败, " + msg;
                }
                nowdingwei.this.runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
//                        Toast.makeText( nowdingwei.this, authinfo, Toast.LENGTH_LONG).show();
                    }
                });
            }

            public void initSuccess() {
                //  Toast.makeText( MainActivity.this, "百度导航引擎初始化成功", Toast.LENGTH_SHORT).show();
                hasInitSuccess = true;
                initSetting();
            }

            public void initStart() {
                // Toast.makeText( MainActivity.this, "百度导航引擎初始化开始", Toast.LENGTH_SHORT).show();
            }

            public void initFailed() {
                //Toast.makeText( MainActivity.this, "百度导航引擎初始化失败", Toast.LENGTH_SHORT).show();
            }
        }, null);
    }
    //private CoordinateType mCoordinateType = null;
    private void routeplanToNavi(boolean shif) {

        if (!hasInitSuccess) {
            Toast.makeText(nowdingwei.this, "还未初始化!", Toast.LENGTH_SHORT).show();
        }
        // 权限申请
        if (android.os.Build.VERSION.SDK_INT >= 23) {
            // 保证导航功能完备
            if (!hasCompletePhoneAuth()) {
                if (!hasRequestComAuth) {
                    hasRequestComAuth = true;
                    this.requestPermissions(authComArr, authComRequestCode);
                    return;
                } else {
                    //  Toast.makeText(MainActivity.this, "没有完备的权限!", Toast.LENGTH_SHORT).show();
                }
            }
        }
//        BNRoutePlanNode sNode = null;
//        BNRoutePlanNode eNode = null;

        BNRoutePlanNode sNode=null;
        BNRoutePlanNode eNode=null;
        sNode = new BNRoutePlanNode(latlngl.longitude, latlngl.latitude, "我的地点", null, GCJ02);
        eNode = new BNRoutePlanNode(ne.longitude, ne.latitude, "我的目的地", null,GCJ02);

        if (sNode != null && eNode != null) {
            List<BNRoutePlanNode> list = new ArrayList<BNRoutePlanNode>();
            list.add(sNode);
            list.add(eNode);

            // 开发者可以使用旧的算路接口，也可以使用新的算路接口,可以接收诱导信息等
            // BaiduNaviManager.getInstance().launchNavigator(this, list, 1, true, new DemoRoutePlanListener(sNode));
            BaiduNaviManager.getInstance().launchNavigator(this, list, 1, shif, new nowdingwei.DemoRoutePlanListener(sNode)
            );
        }

    }
    public class DemoRoutePlanListener implements BaiduNaviManager.RoutePlanListener {

        private BNRoutePlanNode mBNRoutePlanNode = null;

        public DemoRoutePlanListener(BNRoutePlanNode node) {
            mBNRoutePlanNode = node;
        }

        @Override
        public void onJumpToNavigator() {
            /*
             * 设置途径点以及resetEndNode会回调该接口
             */
            Intent intent = new Intent(nowdingwei.this, BNDemoGuideActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable(ROUTE_PLAN_NODE, (BNRoutePlanNode) mBNRoutePlanNode);
            intent.putExtras(bundle);
            startActivity(intent);

        }

        @Override
        public void onRoutePlanFailed() {
            // TODO Auto-generated method stub
            Toast.makeText(nowdingwei.this, "算路失败", Toast.LENGTH_SHORT).show();
        }
    }
    private void initSetting() {
        // BNaviSettingManager.setDayNightMode(BNaviSettingManager.DayNightMode.DAY_NIGHT_MODE_DAY);
        BNaviSettingManager
                .setShowTotalRoadConditionBar(BNaviSettingManager.PreViewRoadCondition.ROAD_CONDITION_BAR_SHOW_ON);
        BNaviSettingManager.setVoiceMode(BNaviSettingManager.VoiceMode.Veteran);
        // BNaviSettingManager.setPowerSaveMode(BNaviSettingManager.PowerSaveMode.DISABLE_MODE);
        BNaviSettingManager.setRealRoadCondition(BNaviSettingManager.RealRoadCondition.NAVI_ITS_ON);
        BNaviSettingManager.setIsAutoQuitWhenArrived(true);
        Bundle bundle = new Bundle();
        // 必须设置APPID，否则会静音
        bundle.putString(BNCommonSettingParam.TTS_APP_ID, "9996592");
        BNaviSettingManager.setNaviSdkParam(bundle);
    }








    private void getdata(LatLng ll) {
        GeoCoder geoCoder = GeoCoder.newInstance();
        //
        OnGetGeoCoderResultListener listener = new OnGetGeoCoderResultListener() {
            // 反地理编码查询结果回调函数
            @Override
            public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
                if (result == null
                        || result.error != SearchResult.ERRORNO.NO_ERROR) {
                    // 没有检测到结果
                    Toast.makeText(nowdingwei.this, "抱歉，未能找到结果",
                            Toast.LENGTH_LONG).show();
                    return;
                }
                poiInfos = (ArrayList<PoiInfo>) result.getPoiList();
//                adapter = new PoiListAdapter(MainActivity.this, poiInfos);  适配器
//                iv_item.setAdapter(adapter);
//                adapter.notifyDataSetChanged();

            }

            // 地理编码查询结果回调函数
            @Override
            public void onGetGeoCodeResult(GeoCodeResult result) {
                if (result == null
                        || result.error != SearchResult.ERRORNO.NO_ERROR) {
                    // 没有检测到结果
                }
            }
        };
        // 设置地理编码检索监听者
        geoCoder.setOnGetGeoCodeResultListener(listener);
        //
        geoCoder.reverseGeoCode(new ReverseGeoCodeOption().location(ll));
    }
    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        mMapView.onPause();
    }
    @Override
    protected void onStart() {
        super.onStart();
        mBaiduMap.setMyLocationEnabled(true);// 打开定位图层
        if (!locationClient.isStarted()) {
            locationClient.start();
            //开启方向传感器

            // startService(new Intent(MainActivity.this,GpsInfoCollectionService.class));
        }
    }
    @Override
    protected void onStop() {
        super.onStop();
        mBaiduMap.setMyLocationEnabled(false);// 关闭定位图层
        locationClient.stop();


    }

}
